__author__ = 'shawhen'

try:
    from PyQt5.QtCore import *


    class ExceptionCatcher(QObject):
        sigException = pyqtSignal(str)

        def __init__(self, parent=None):
            super(ExceptionCatcher, self).__init__(parent)

        def exception(self, e_type, e_value, e_traceback):
            cur_tb = e_traceback
            while True:
                next_tb = cur_tb.tb_next
                if next_tb is None:
                    break
                else:
                    cur_tb = next_tb
            last_tb = cur_tb

            import traceback
            traceback.print_exception(e_type, e_value, e_traceback)
            exc_text = "".join(traceback.format_exception(e_type, e_value, e_traceback))

            last_tb_frame_file = last_tb.tb_frame.f_locals.get("__file__", "")
            print("last tb file:", last_tb_frame_file)
            exc_text += "last tb file:"+last_tb_frame_file+"\r\n"

            self.sigException.emit(exc_text)
except ImportError as e:
    class ExceptionCatcher():
        def __init__(self):
            pass

        def exception(self, e_type, e_value, e_traceback):
            cur_tb = e_traceback
            while True:
                next_tb = cur_tb.tb_next
                if next_tb is None:
                    break
                else:
                    cur_tb = next_tb
            last_tb = cur_tb

            import traceback
            traceback.print_exception(e_type, e_value, e_traceback)
            exc_text = "".join(traceback.format_exception(e_type, e_value, e_traceback))

            last_tb_frame_file = last_tb.tb_frame.f_locals.get("__file__", "")
            print("last tb file:", last_tb_frame_file)
            exc_text += "last tb file:"+last_tb_frame_file+"\r\n"

g__eccatcher = ExceptionCatcher()